﻿# ======================
# Чудодейственный скрипт конвертирует все файлы в каталоге
# из любой кодировки в UTF-8
# для работы требуется chardet-2.2.1-py2.py3-none-any
# ======================
import os
import chardet

def check_codepage(pathfolder):
    print "check codepage in folder", pathfolder
    decodeCount = 1
    filepath = ""
    #get list all files
    files = os.listdir(pathfolder)
    for top, dirs, files in os.walk(pathfolder):
        for nm in files:
            if any([nm.endswith(extension) for extension in '.c,.cpp,.h'.split(',')]):
                onefile = open(os.path.join(top, nm), 'r')
                text = onefile.read()
                enc = chardet.detect(text).get("encoding")
                #detect non utf-8 codepage!
                if enc and enc.lower() != 'utf-8' and enc.lower()!='ascii':
                    #test
                    print "detected", nm
                    continue
                    #make encode
                    text = text.decode(enc)
                    text = text.encode("utf-8")
                    with open(os.path.join(top, nm), "wb") as f:
                        f.write(text)
                        print '#', decodeCount, nm , "from", enc, "to utf-8 converted!"
                        decodeCount = decodeCount + 1
    
print('begin');
check_codepage("D:/projects/bb_and_bt/trunk/client/BattleWizards/Classes/")
print('end');
